
package com.shop.cloud.weixin.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.weixin.admin.config.open.WxOpenConfiguration;
import com.shop.cloud.weixin.admin.mapper.WxAppMapper;
import com.shop.cloud.weixin.common.constant.WxConstant;
import com.shop.cloud.weixin.common.constant.WxReturnCode;
import com.shop.cloud.weixin.common.entity.WxApp;
import com.shop.cloud.weixin.common.entity.WxMaNicknameAudit;
import com.shop.cloud.weixin.admin.mapper.WxMaNicknameAuditMapper;
import com.shop.cloud.weixin.admin.service.WxMaNicknameAuditService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.open.bean.result.WxFastMaQueryNicknameStatusResult;
import org.springframework.stereotype.Service;

/**
 * 小程序名称审核结果
 *
 * @author
 * @date 2022-03-03 15:26:16
 */
@Service
@AllArgsConstructor
public class WxMaNicknameAuditServiceImpl extends ServiceImpl<WxMaNicknameAuditMapper, WxMaNicknameAudit> implements WxMaNicknameAuditService {

	private final WxAppMapper wxAppMapper;

	@Override
	public void queryNicknameAudit(String id) {
		WxMaNicknameAudit wxMaNicknameAudit = baseMapper.selectById(id);
		WxFastMaQueryNicknameStatusResult wxFastMaQueryNicknameStatusResult;
		try {
			//调用微信服务查询
			wxFastMaQueryNicknameStatusResult = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMaServiceByAppid(wxMaNicknameAudit.getAppId()).getBasicService().querySetNicknameStatus(wxMaNicknameAudit.getAuditId());
			if(!WxReturnCode.SUC_0.getCode().equals(wxFastMaQueryNicknameStatusResult.getErrcode())){
				throw new RuntimeException(wxFastMaQueryNicknameStatusResult.getErrmsg());
			}
			//更新本地数据
			wxMaNicknameAudit.setNickname(wxFastMaQueryNicknameStatusResult.getNickname());
			wxMaNicknameAudit.setRet(String.valueOf(wxFastMaQueryNicknameStatusResult.getAuditStat()));
			wxMaNicknameAudit.setReason(wxFastMaQueryNicknameStatusResult.getFailReason());
			baseMapper.updateById(wxMaNicknameAudit);
			if(WxConstant.WX_NICKNAME_AUDIT_RET_3.equals(wxMaNicknameAudit.getRet())){
				//成功则更新Wxapp
				WxApp wxApp = wxAppMapper.selectById(wxMaNicknameAudit.getAppId());
				wxApp.setName(wxMaNicknameAudit.getNickname());
				wxAppMapper.updateById(wxApp);
			}
		} catch (WxErrorException e) {
			e.printStackTrace();
			Integer errorCode = e.getError().getErrorCode();
			throw new RuntimeException(WxReturnCode.getMsg("ERR_"+errorCode, e));
		}
	}
}
